package com.weimob.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @program: xh-learn-record
 * @description:
 * @author: sch
 * @create: 2022-12-20 19:17
 **/
public class A009_CustomProducerTransactions {
    public static void main(String[] args) {
        //1,创建kafka生产者对象
        //1.1 创建生产者配置对象
        Properties properties = new Properties();
        //1.2 添加kafka配置信息
        //botstrap.servers 信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.3:9092,192.168.1.3:9093,192.168.1.3:9094");
        //k,v序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        // 设置事务 id（必须），事务 id 任意起名
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transaction_id_0");
        //1.3 创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        //2,发送消息
        // 初始化事务
        kafkaProducer.initTransactions();
        // 开启事务
        kafkaProducer.beginTransaction();
        try {
            for (int i = 0; i < 10; i++) {
                kafkaProducer.send(new ProducerRecord<String, String>("first", "A009 hell xhx" + i));
            }
            int i = 1/0;
            // 提交事务
            kafkaProducer.commitTransaction();
        }catch (Exception e){
            // 终止事务
            kafkaProducer.abortTransaction();
        }finally {
            //3,关闭资源
            kafkaProducer.close();
        }

        KafkaConsumer<String, String> kafkaConsumer
                = new KafkaConsumer<String, String>(new Properties());
        kafkaConsumer.poll(100);

    }
}
